﻿using System.Reactive.Subjects;
using StackExchange.Redis;

namespace Growatt.ShinebusServiceUploadPack.Service
{
    public class RedisHelper
    {
        public  readonly ISubject<List<EntityObjectData>> subjecRealTimeUpdateMessageMessageStatus = new Subject<List<EntityObjectData>>();
     public   MessageChannel<List<EntityObjectData>> messageChannel = null;

        public RedisHelper()
        {
            string redisip = "20.60.2.23";
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect($"{redisip}:6379"); //连接Redis
            messageChannel = new MessageChannel<List<EntityObjectData>>(subjecRealTimeUpdateMessageMessageStatus);
            try
            {
                // 尝试连接到 Redis 服务器
                IDatabase db = redis.GetDatabase();
                // 检查连接是否成功
                if (redis.IsConnected)
                {
                    subjecRealTimeUpdateMessageMessageStatus.Subscribe(
                        async (o) =>
                        {
                            try
                            {
                                var data = o.Select(x => x).ToList();
                                for (global::System.Int32 i = 0; i < data.Count; i++)
                                {
                                    // 向频道 'channel1' 发布消息
                                    long subscribers = db.Publish("channelFeishu", string.Join("", data[i].DoubleList.Select(x => x.ToString()).ToArray()));
                                }
                            }
                            catch (Exception) { }
                        }
                    );
                }
                else
                {
                    Console.WriteLine("Connection to Redis failed.");
                    return;
                }
            }
            catch (Exception ex)
            {
                // 捕获并输出异常信息
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
          
        }
    }
}
